package problems;

import lib.MathLib;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;

public class Euler049 extends AbstractEuler {

	@Override
	public Number calculate() {
		nextSequence:
		for (int first = 1001; first <= 9995; first += 2) {
			if (first == 1487) continue nextSequence; //the example from the problem statement
			if (!MathLib.isPrime(first)) continue nextSequence;
			nextInterval:
			for (int interval = 2; first + 2*interval <= 9999; interval += 2) {
				int second = first + interval;
				if (!MathLib.isPrime(second)) continue nextInterval;
				int third = second + interval;
				if (!MathLib.isPrime(third)) continue nextInterval;
				if (arePermutations(first, second, third)) {
					return Long.valueOf(
						String.valueOf(first) +
						String.valueOf(second) +
						String.valueOf(third)
					);
				}
			}
		}
		fail("didn't find any sequences that were permutations and all prime");
		return null;
	}
	
	private boolean arePermutations(int first, int second, int third) {
		Multiset<Character> firstDigits = HashMultiset.create(4);
		Multiset<Character> secondDigits = HashMultiset.create(4);
		Multiset<Character> thirdDigits = HashMultiset.create(4);
		
		for (int i = 0; i <= 3; i++) {
			firstDigits.add(String.valueOf(first).charAt(i));
			secondDigits.add(String.valueOf(second).charAt(i));
			thirdDigits.add(String.valueOf(third).charAt(i));
		}
		
		return firstDigits.equals(secondDigits) && firstDigits.equals(thirdDigits);
		
	}

	@Override
	protected Number getCorrectAnswer() {
		return 296962999629L;
	}

}
